#include <iostream>
#include <memory>
using namespace std;

#include <unistd.h>
#include <pthread.h>
// 使用互斥锁实现读写锁,写者优先
pthread_mutex_t r_count_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t w_count_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t rwcond = PTHREAD_COND_INITIALIZER;
int reader = 0;
int writer = 0;
int waiting_writers = 0; // 等待写者的其他写者数量

// 读者加锁
void read_lock()
{
    pthread_mutex_lock(&r_count_lock);
    // 如果有其他读者，就需要等待
    while (writer > 0 || waiting_writers > 0)
        pthread_cond_wait(&rwcond, &r_count_lock);
    reader++;
    pthread_mutex_unlock(&r_count_lock);
}

// 读者解锁
void read_unlock()
{
    pthread_mutex_lock(&r_count_lock);
    reader--;
    // 没有读者通知写者写数据
    if (reader == 0)
        pthread_cond_signal(&rwcond);

    pthread_mutex_unlock(&r_count_lock);
}

// 写者加锁
void write_lock()
{
    // 增加等待写者的数量
    pthread_mutex_lock(&w_count_lock);
    waiting_writers++;
    pthread_mutex_unlock(&w_count_lock);

    // 判断有无读者或者写者正在写数据
    pthread_mutex_lock(&r_count_lock);
    while (reader > 0 || writer > 0)
        pthread_cond_wait(&rwcond, &r_count_lock);
    pthread_mutex_unlock(&r_count_lock);

    // 减少等待写者的数量
    pthread_mutex_lock(&w_count_lock);
    waiting_writers--;
    pthread_mutex_unlock(&w_count_lock);
}

// 写者加锁
void write_unlock()
{
    pthread_mutex_lock(&r_count_lock); // 写者优先
    writer--;
    pthread_cond_broadcast(&rwcond);   // 唤醒其他读者写者
    pthread_mutex_lock(&r_count_lock); // 写者优先
}

int main()
{
    return 0;
}